package com.ys.controller.api.hr;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ys.config.MenuId;
import com.ys.entity.sys.YsCol;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.entity.hr.ThrOperateCompanyBeian;
import com.ys.service.flow.YspTaskService;
import com.ys.service.hr.ThrOperateCompanyBeianService;
import com.ys.service.sys.CommonApiService;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/thrOperateCompanyBeian")
public class ApiInterThrOperateCompanyBeianController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterThrOperateCompanyBeianController.class);
	
	@Autowired
	private CommonApiService<ThrOperateCompanyBeian> commonApiService;
	@Autowired
	private ThrOperateCompanyBeianService thrOperateCompanyBeianService;
	@Autowired
	private YspTaskService yspTaskService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public ThrOperateCompanyBeian setSeachSql(ThrOperateCompanyBeian cond){

        cond.addLeftJoin("TS_UserChange B on B.Id = A.OperatorChangeId")
                .addField("B.UserId operatorUserId")//运营人工号
                .addField("B.UserName operatorUserName")//运营人
                .addField("B.RoleName roleName")//运营人岗位
                .addField("B.DeptName deptName");//运营人部门

        cond.addLeftJoin("THR_CanvassApplyItem C on C.Id = A.CanvassApplyItemId AND 1=1")
                .addField("C.InvestType investType")//招商类型
                .addField("C.CostStandard costStandard");//费用标准

        cond.addLeftJoin("TS_UserChange U on U.Id = A.CreateChangeId")
                .addField("U.UserId createUserId")//制单人工号
                .addField("U.UserName createUserName")//制单人
                .addField("U.RoleName createRoleName")//制单人岗位
                .addField("U.DeptName createDeptName");//制单人部门

        cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditTime");//审核时间

        cond.setOrderby("A.Code desc");
        //权限
        cond = commonApiService.dataAuth(MenuId.THR_OperateCompanyBeian, cond);
        return  cond;
    }

	@RequiresPermissions("thrOperateCompanyBeian:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute ThrOperateCompanyBeian cond
			){
        cond = setSeachSql(cond);
		return commonApiService.searchLay(cond);
	}

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute ThrOperateCompanyBeian cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.THR_OperateCompanyBeian)
                    //.where("A.Code NOT IN ( 'canvassApplyItemId','operatorChangeId')")
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<ThrOperateCompanyBeian> util = new ExportExcelUtils<>(new ThrOperateCompanyBeian());
            String toFilePath = util.exportExcel(listData, listField, "运营公司备案");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
	 * 运营公司弹出框调用
	 */
	@RequestMapping("/searchForModal")
    @ResponseBody
	public LayuiTableVoJA searchForModal(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute ThrOperateCompanyBeian cond
			){
		cond.setEffectStock(1);
		return commonApiService.searchLay(cond);
	}
	
	/**
	 * 新增
	 */
	@PostMapping("/add")
    @ResponseBody
	public R add(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			return thrOperateCompanyBeianService.add(params, MenuId.THR_OperateCompanyBeian);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}


    /**
     * 新增-关联招商信息申请单
     */
    @PostMapping("/addByCanvassApply")
    @ResponseBody
    public R addByCanvassApply(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return thrOperateCompanyBeianService.add(params, MenuId.THR_OperateCompanyBeian_By_CanvassApply);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }
	
	/**
     * 编辑
     */
    @PostMapping("/edit")
    @ResponseBody
    public R edit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return thrOperateCompanyBeianService.edit(params, MenuId.THR_OperateCompanyBeian);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 编辑-关联招商信息申请单
     */
    @PostMapping("/editByCanvassApply")
    @ResponseBody
    public R editByCanvassApply(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return thrOperateCompanyBeianService.edit(params, MenuId.THR_OperateCompanyBeian_By_CanvassApply);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }
	
	/**
	 * 删除
	 */
//	@RequiresPermissions("thrOperateCompanyBeian:add")
	@PostMapping("/deleteTrue")
    @ResponseBody
	public R deleteTrue(HttpServletRequest request, Long id){
		try {
			return thrOperateCompanyBeianService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转通过
	 */
	@PostMapping("/flowPass")
    @ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		try {
			return thrOperateCompanyBeianService.flowPass(id, ShiroUtils.getUserId());
		} catch (UncategorizedSQLException e) {
			e.printStackTrace();
			return R.error(e.getCause().getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@PostMapping("/flowRefuse")
    @ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		
		ThrOperateCompanyBeian entity = new ThrOperateCompanyBeian().setId(id).queryFirst();
		String bid = entity.getBid();
		try {
			return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}


	/**
	 * 流转退回
	 */
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		ThrOperateCompanyBeian entity = new ThrOperateCompanyBeian().setId(id).queryFirst();
		String bid = entity.getBid();
		try {
			return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			logger.error("驳回出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		}
	}

}
